package com.tencreat.account.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.AjaxResult;
import com.tencreat.common.core.domain.entity.SysUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BusinessType;
import com.tencreat.common.enums.account.TencreatTips;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.poi.ExcelNewUtil;
import com.tencreat.common.utils.poi.ExcelUtil;
import com.tencreat.common.utils.sign.Md5Utils;
import com.tencreat.domain.account.AccountLoginCheck;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.account.vo.MallSupplierStaticsVo;
import com.tencreat.domain.account.vo.MallUsellVO;
import com.tencreat.domain.account.vo.MallUserStaticsVo;
import com.tencreat.domain.mall.MallCoupon;
import com.tencreat.domain.mall.vo.MallUserVO2;
import com.tencreat.domain.mall.vo.MallUserVO3;
import com.tencreat.service.account.IAccountLoginCheckService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.system.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户Controller
 *
 * @author tencreat
 * @date 2021-08-15
 */
@Api(tags = "用户api")
@RestController
@RequestMapping("/mall/user")
public class AdminMallUserController extends BaseController {
    @Autowired
    private IMallUserService mallUserService;
    @Autowired
    private IAccountLoginCheckService accountLoginCheckService;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询用户列表
     */
    @ApiOperation(value = "查询用户列表")
    @PreAuthorize("@ss.hasPermi('mall:user:list')")
    @PostMapping("/list")
    public HttpResult<IPage<MallUser>> list(@RequestBody MallUser mallUser) {
        QueryWrapper<MallUser> wrapper = new QueryWrapper<>();
        wrapper.eq(mallUser.getUuid() != null, "uuid", mallUser.getUuid());
        wrapper.eq(mallUser.getReferrerUuid() != null, "referrer_uuid", mallUser.getReferrerUuid());
        wrapper.like(StrUtil.isNotBlank(mallUser.getMobile()), "mobile", mallUser.getMobile());
        wrapper.eq(mallUser.getStatus() != null, "status", mallUser.getStatus());
        if (mallUser.getUuid() != null) {
            wrapper.like("uuid", mallUser.getUuid());
        }
        if (mallUser.getRealStatus() != null) {
            wrapper.like("real_status", mallUser.getRealStatus());
        }
        if (mallUser.getStatus() != null){
            wrapper.like("status", mallUser.getStatus());
        }
        if (mallUser.getReferrerUuid() != null){
            wrapper.like("referrer_uuid", mallUser.getReferrerUuid());
        }
        if (mallUser.getStartTime() != null) {
            wrapper.gt("create_time", mallUser.getStartTime());
        }
        if (mallUser.getEndTime() != null) {
            wrapper.lt("create_time", mallUser.getEndTime());
        }
        if (mallUser.getSortStr() != null && mallUser.getSortDesc() != null){
                if (mallUser.getSortDesc().equals("ascending")){
                    wrapper.orderByAsc(mallUser.getSortStr());
                }
                wrapper.orderByDesc(mallUser.getSortStr());
            }else {
            wrapper.orderByDesc("create_time");
        }
        Page<MallUser> page = new Page<>(mallUser.getPageNum(), mallUser.getPageSize());
        Page<MallUser> userPage = mallUserService.page(page, wrapper);
        List<MallUser> records = userPage.getRecords();
        List<MallUser> collect = records.stream().peek(item -> {
            if(item.getSupplier() == AllEnum.SupplierGoods.YES.getType()){
                SysUser user = sysUserService.selectUserByPhone(item.getMobile(),2);
                item.setSupplierName(user.getNickName());
                item.setGoodsPayment(user.getSupplierEarnings());
            }
//            //消费券数量
//            Integer consumerRollCount = mallUserService.lambdaQuery().eq(MallUser::getConsumerRoll, item.getConsumerRoll()).count();
//            //提货单数量
//            Integer goodsRollCount = mallUserService.lambdaQuery().eq(MallUser::getGoodsRoll, item.getGoodsRoll()).count();
//            item.setConsumerRoll(BigDecimal.valueOf(consumerRollCount));
//            item.setGoodsRoll(BigDecimal.valueOf(goodsRollCount));

        }).collect(Collectors.toList());
        userPage.setRecords(collect);
        return HttpResult.ok(userPage);
    }

    /**
     * 导出用户列表
     */
    @ApiOperation(value = "导出用户列表")
    @PreAuthorize("@ss.hasPermi('mall:user:export')")
    @Log(title = "用户管理>用户列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@RequestBody MallUser mallUser, HttpServletResponse response) {
        QueryWrapper<MallUser> wrapper = new QueryWrapper<>();
        wrapper.eq(mallUser.getUuid() != null, "uuid", mallUser.getUuid());
        wrapper.eq(mallUser.getReferrerUuid() != null, "referrer_uuid", mallUser.getReferrerUuid());
        wrapper.like(StrUtil.isNotBlank(mallUser.getMobile()), "mobile", mallUser.getMobile());
       // wrapper.eq(mallUser.getUserLevel() != null, "user_level", mallUser.getUserLevel());
        wrapper.eq(mallUser.getStatus() != null, "status", mallUser.getStatus());
        if (mallUser.getStartTime() != null) {
            wrapper.gt("create_time", mallUser.getStartTime());
        }
        if (mallUser.getEndTime() != null) {
            wrapper.lt("create_time", mallUser.getEndTime());
        }
        if (mallUser.getSortStr() != null && mallUser.getSortDesc() != null){
            if (mallUser.getSortDesc().equals("ascending")){
                wrapper.orderByAsc(mallUser.getSortStr());
            }
            wrapper.orderByDesc(mallUser.getSortStr());
        }else {
            wrapper.orderByDesc("create_time");
        }
        Page<MallUser> page = new Page<>(1, Integer.MAX_VALUE);
        Page<MallUser> userPage = mallUserService.page(page, wrapper);
        List<MallUser> records = userPage.getRecords();
        List<MallUser> collect = records.stream().peek(item -> {
            if (null == item.getBalance()){
                item.setBalance(BigDecimal.ZERO);
            }
            //item.setIsVipDesc(item.getUserLevel().getDesc());
            if (item.getStatus() == 0){
                item.setStatusDesc("正常");
            }
            if (item.getStatus() == 1){
                item.setStatusDesc("禁用");
            }
            if (item.getStatus() == 2){
                item.setStatusDesc("注销");
            }
            if(item.getSupplier() == AllEnum.SupplierGoods.YES.getType()){
                SysUser user = sysUserService.selectUserByPhone(item.getMobile(),2);
                item.setSupplierName(user.getNickName());
                item.setGoodsPayment(user.getSupplierEarnings());
            }
        }).collect(Collectors.toList());
        userPage.setRecords(collect);
        List<MallUser> list = userPage.getRecords();
        if (mallUser.getType() == 1){
            List<MallUserVO2> mallUserVO2List = JSONObject.parseArray(JSONObject.toJSONString(list), MallUserVO2.class);
            ExcelNewUtil.exportExcel(mallUserVO2List, "用户列表", MallUserVO2.class, response);
        }
    }

    /**
     * 获取用户详细信息
     */
    @ApiOperation(value = "获取用户详细信息")
    @PreAuthorize("@ss.hasPermi('mall:user:query')")
    @PostMapping(value = "/getInfo")
    public HttpResult<MallUser> getInfo(@RequestBody ReqIdParam id) {
        return HttpResult.ok(mallUserService.selectMallUserById(id));
    }

    /**
     * 通过用户uuid获取详细信息
     */
    @ApiOperation(value = "通过用户uuid获取详细信息")
    @PreAuthorize("@ss.hasPermi('mall:user:query')")
    @PostMapping(value = "/getInfoByUuid")
    public HttpResult<MallUser> getInfoByUuid(@RequestBody ReqIdParam id) {
        return HttpResult.ok(mallUserService.lambdaQuery().eq(MallUser::getUuid, id.getId()).one());
    }

    /**
     * 新增用户
     */
    @ApiOperation(value = "新增用户")
    @PreAuthorize("@ss.hasPermi('mall:user:add')")
    @Log(title = "用户管理>用户列表", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public HttpResult<Boolean> add(@RequestBody MallUser mallUser) {
        mallUser.setUuid((long) mallUserService.generateUUID());
        String password = mallUser.getPassword();
        //默认使用8888
        if (mallUser.getReferrerUuid() == null) {
            mallUser.setReferrerUuid(AllEnum.SUPER_UUID);
        }
        Integer count = mallUserService.lambdaQuery().eq(MallUser::getMobile, mallUser.getMobile()).count();
        Integer count2 = accountLoginCheckService.lambdaQuery().eq(AccountLoginCheck::getPhone, mallUser.getMobile()).count();
        if (count != 0 || count2 != 0) {
            return HttpResult.error("该手机号码已存在");
        }
        MallUser mallUserMobile = mallUserService.selectmobileByUuid(mallUser.getReferrerUuid());
        //将该推荐人手机号码赋值给新建用户的推荐人手机号
        mallUser.setUpMobile(mallUserMobile.getMobile());
        //注册账号是 应该先注册关键账号
        AccountLoginCheck loginCheck = new AccountLoginCheck();
        loginCheck.setPassword(Md5Utils.hash(password));
        loginCheck.setPhone(mallUser.getMobile());
        loginCheck.setCreateTime(LocalDateTime.now());
        loginCheck.setUuid(mallUser.getUuid());
        accountLoginCheckService.insertAccountLoginCheck(loginCheck);
        mallUser.setPassword(Md5Utils.hash(password));

        MallUser mallUserServiceOne = mallUserService
                .getOne(new QueryWrapper<MallUser>().eq("uuid", mallUser.getReferrerUuid()));
        if (mallUserServiceOne == null) {
            return HttpResult.error(TencreatTips.Account.RECOMMEND_CODE_NOT_EXIST);
        }
        List<String> classRelationsList = StrUtil.splitTrim(mallUserServiceOne.getClassRelations(), ",");
        classRelationsList.add(mallUser.getReferrerUuid().toString());
        mallUser.setTier(classRelationsList.size());
        mallUser.setClassRelations(StrUtil.join(",", classRelationsList));

        return to(mallUserService.insertMallUser(mallUser));
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @PreAuthorize("@ss.hasPermi('mall:user:edit')")
    @Log(title = "用户管理>用户列表", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public HttpResult<Boolean> edit(@RequestBody MallUser mallUser) {
        return to(mallUserService.editMallUser(mallUser));
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户")
    @PreAuthorize("@ss.hasPermi('mall:user:remove')")
    @Log(title = "用户管理>用户列表", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public HttpResult<Boolean> remove(@RequestBody ReqIdsParam ids) {
        return to(mallUserService.deleteMallUserByIds(ids));
    }

    /**
     * 最新用户
     */
    @ApiOperation(value = "最新用户")
    @PreAuthorize("@ss.hasPermi('mall:user:new_user')")
    @PostMapping("/new_user")
    public HttpResult<List<MallUser>> getNewUser(@RequestBody MallUser mallUser) {
        return mallUserService.newUser(mallUser);
    }


    /**
     * 查询第一级组织架构
     */
    @ApiOperation(value = "查询组织架构")
    @PreAuthorize("@ss.hasPermi('mall:user:grouplist')")
    @PostMapping("/grouplist")
    public List<MallUser> grouplist() {
        MallUser mallUser = new MallUser();
        List<MallUser> mallUserList = new ArrayList<>();

        //第一次查询时编号为空,查询出第一级平台账号
        mallUserList = mallUserService.selectALLOneByUuid();
        return mallUserList;
    }

    /**
     * 查询第二级组织架构
     */
    @ApiOperation(value = "查询组织架构")
    @PreAuthorize("@ss.hasPermi('mall:user:groupdownlist')")
    @PostMapping("/groupdownlist")
    public List<MallUser> grouplist(@RequestBody ReqIdParam id) {
        MallUser mallUser = new MallUser();
        List<MallUser> mallUserList = new ArrayList<>();
        //第一二次查询时,查询出下一级平台账号
        mallUserList = mallUserService.selectOneByUuid(id.getId());
        mallUserList.forEach(i->{
            Integer count = mallUserService.lambdaQuery().eq(MallUser::getReferrerUuid, i.getUuid()).count();
            i.setHasKids(count>0);
        });
        return mallUserList;
    }

    @ApiOperation(value = "查询用户是否存在下级")
    @PostMapping("/queryHasKid")
    public HttpResult<Integer> queryHasKid(@RequestBody ReqIdParam id) {
        //第一二次查询时,查询出下一级平台账号
        Integer count = mallUserService.lambdaQuery().eq(MallUser::getReferrerUuid, id.getId()).count();
        return HttpResult.ok(count);
    }


    /**
     * 查询用户列表
     */
    @ApiOperation(value = "查询用户列表")
    @PreAuthorize("@ss.hasPermi('mall:user:list')")
    @GetMapping("/userlist")
    public List<MallUser> userlist() {
        return mallUserService.userList();
    }


    /**
     * 修改用户状态
     */
    @ApiOperation(value = "修改用户状态")
    @Log(title = "用户管理>用户列表", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editUserStatus")
    public HttpResult<Boolean> editUserStatus(@RequestBody MallUser mallUser) {
        MallUser user = mallUserService.getById(mallUser.getId());
        user.setStatus(mallUser.getStatus());
        user.setUpdateTime(LocalDateTime.now());
        return to(mallUserService.updateById(user));
    }

/*    *//**
     * 修改用户vip到期时间
     *//*
    @ApiOperation(value = "修改用户vip到期时间")
    @Log(title = "用户管理>会员列表", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editUserVipEndTime")
    public HttpResult<Boolean> editUserVipEndTime(@RequestBody MallUser mallUser) {
        MallUser user = mallUserService.getById(mallUser.getId());
        user.setSVipEndTime(mallUser.getVipEndTime());
        return to(mallUserService.updateById(user));
    }*/

    @ApiOperation("搜索用户")
    @GetMapping("/search")
    public HttpResult<Object> search(@RequestParam("uuid") Long uuid, @RequestParam("mobile") String mobile) {
        if(uuid==null && StringUtils.isBlank(mobile)){
            return HttpResult.error("请输入...");
        }
        List resultList = new ArrayList();
        // 当前用户
        MallUser accountUser = mallUserService.lambdaQuery()
                .eq(uuid!=null,MallUser::getUuid, uuid)
                .eq(StringUtils.isNotBlank(mobile),MallUser::getMobile,mobile)
                .select(MallUser::getId, MallUser::getId,MallUser::getUuid, MallUser::getUsername, MallUser::getReferrerUuid).one();
        if (accountUser == null) {
            return HttpResult.error("未找到搜索用户");
        }
        // 查他的所有上级
        List<MallUser> superList=new ArrayList<>();
        Long referrerUuid = accountUser.getReferrerUuid();
        while (true){
            MallUser one = mallUserService.lambdaQuery().eq(MallUser::getUuid, referrerUuid).one();
            if(one!=null){
                superList.add(one);
                referrerUuid=one.getReferrerUuid();
            }else{
                break;
            }
        }
        // 查看他所有直属下级
        List<MallUser> directlySubList = mallUserService.lambdaQuery().eq(MallUser::getReferrerUuid, accountUser.getUuid())
                .select(MallUser::getId, MallUser::getId,MallUser::getUuid, MallUser::getUsername)
                .list();
        // 拼接用户上下级关系
        Map<String, Object> map = new HashMap<>();
        map.put("id", accountUser.getId());
        map.put("uuid", accountUser.getUuid());
 //       map.put("userLevel", accountUser.getUserLevel());
//        map.put("subordinate", accountUser.getSubordinate());
        map.put("username", accountUser.getUsername());
        map.put("referrerUuid", accountUser.getReferrerUuid());
        // 拼接用户下级关系
        if (directlySubList.size() > 0) {
            List list = new ArrayList();
            for (MallUser item : directlySubList) {
                Map<String, Object> map2 = new HashMap<>();
                List list2 = new ArrayList();
                map2.put("id", item.getId());
                map2.put("uuid", item.getUuid());
 //               map2.put("userLevel", item.getUserLevel());
//                map2.put("subordinate", item.getSubordinate());
                map2.put("username", item.getUsername());
                map2.put("referrerUuid", accountUser.getReferrerUuid());
                List<MallUser> users = mallUserService.selectOneByUuidDown(item.getUuid());
                Map<Long,List<MallUser>> map1 = users.stream().collect(Collectors.groupingBy(MallUser::getReferrerUuid));
                if (map1 != null && map1.get(item.getUuid()) != null) {
                    for (MallUser m2 : map1.get(item.getUuid())) {
                        m2.setChildren(map1.get(m2.getUuid()));
                    }
                    list2.addAll(map1.get(item.getUuid()));
                    map2.put("children",list2);
                }

                list.add(map2);
            }
            map.put("children", list);
        }
        // 拼接用户上级关系
        Map<String, Object> result = new HashMap<>();
        if (superList.size() > 0) {
            for (MallUser item: superList) {
                result = new HashMap<>();
                result.put("id", item.getId());
                result.put("uuid", item.getUuid());
  //              result.put("userLevel", item.getUserLevel());
//                result.put("subordinate", item.getSubordinate());
                result.put("username", item.getUsername());
                result.put("referrerUuid", accountUser.getReferrerUuid());
                List list = new ArrayList();
                list.add(map);
                result.put("children", list);
                map = result;
            }
        } else {
            resultList.add(map);
        }
        resultList.add(result);
        return HttpResult.ok(resultList);
    }


    /**
     * 用户统计
     */
    @ApiOperation(value = "用户统计")
    @PreAuthorize("@ss.hasPermi('mall:user:list')")
    @GetMapping("/queryUserStatistics")
    public HttpResult<MallUserStaticsVo> queryUserStatistics() {
        return HttpResult.ok(mallUserService.queryUserStatistics());
    }
}
